package com.crayfish.materiallearn;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.VelocityTrackerCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;

/**
 * 作者：crayfish(徐杰)
 * 描述：
 * Created by crayfish on 2017/5/5.
 */

public class TrackingActivity extends AppCompatActivity {
    private static final String TAG = "TrackingActivity";

    private VelocityTracker  velocityTracker = null;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tracking);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int index = event.getActionIndex();
        int action = event.getActionMasked();
        int pointerId = event.getPointerId(index);

        switch (action){
            case MotionEvent.ACTION_DOWN:
                if(velocityTracker == null){
                    velocityTracker = VelocityTracker.obtain();
                }else{
                    velocityTracker.clear();
                }
                velocityTracker.addMovement(event);
                break;
            case MotionEvent.ACTION_MOVE:
                velocityTracker.addMovement(event);
                velocityTracker.computeCurrentVelocity(1000);

                Log.d(TAG, "onTouchEvent:X "+ VelocityTrackerCompat.getXVelocity(velocityTracker,pointerId));
                Log.d(TAG, "onTouchEvent:Y "+ VelocityTrackerCompat.getYVelocity(velocityTracker,pointerId));
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                if(null != velocityTracker) {
                    velocityTracker.clear();
                    velocityTracker.recycle();
                    velocityTracker = null;
                }
                break;
        }
        return true;
    }
}
